package com.ruoyi.wechat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.wechat.common.Constants;
import com.ruoyi.wechat.domain.AppUser;
import com.ruoyi.wechat.domain.CodeSession;
import com.ruoyi.wechat.domain.SessionInfo;
import com.ruoyi.wechat.domain.vo.LoginData;
import com.ruoyi.wechat.service.IAppUserService;
import com.ruoyi.wechat.service.IAuthService;
import com.ruoyi.wechat.utils.RedisHelper;
import com.ruoyi.wechat.utils.WechatHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;

@Service
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private IAppUserService appUserService;

    @Override
    public LoginData pwdAuth(String account, String password) {
        return null;
    }

    @Override
    public LoginData openidAuth(String code) {
        //获取微信会话密钥
        CodeSession codeSession = WechatHelper.getCodeSession(code);
        String openid = codeSession.getOpenid();
        String sessionKey = codeSession.getSessionKey();
        //根据openid查询
        AppUser appUser = appUserService.getByOpenid(openid);
        //如果用户不存在，则新增一个用户，并设置openid
        if (ObjectUtils.isEmpty(appUser)) {
            appUser = new AppUser();
            appUser.setOpenid(openid);
            appUserService.save(appUser);
        }

        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setSessionKey(sessionKey);
        sessionInfo.setAppUser(appUser);
        LoginData loginData = buildLoginData(sessionInfo);
        return loginData;
    }

    @Override
    public LoginData smsAuth(String phone, String verifyCode) {
        return null;
    }


    /**
     * 创建登录返回信息
     *
     * @param sessionInfo
     * @return
     */
    private LoginData buildLoginData( SessionInfo sessionInfo) {
        //生成口令
        String token = UUID.randomUUID().toString();
        String key = Constants.Login.TOKEN_KEY_PRE + token;
        RedisHelper.setEx(key, 3600L, JSON.toJSONString(sessionInfo));
        //构建登录数据
        LoginData data = new LoginData();
        LoginData.UserInfo userInfo = new LoginData.UserInfo();
        BeanUtils.copyProperties(sessionInfo.getAppUser(), userInfo);
        data.setUserInfo(userInfo);
        data.setToken(token);
        return data;
    }

}
